package com.flyduck.mall.oms.h5.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.flyduck.mall.oms.domain.OmsOrder;
import com.flyduck.mall.oms.h5.service.H5DeliveryService;
import com.flyduck.mall.oms.manager.OmsOrderManager;
import com.flyduck.mall.oms.utils.KdApiSearchUtils;
import com.flyduck.mall.oms.h5.vo.H5DeliveryRespVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * H5DeliveryServiceImpl
 * </p>
 *
 * @author flyduck
 * @since 2024-07-24
 */
@Slf4j
@Service
public class H5DeliveryServiceImpl implements H5DeliveryService {

    @Resource
    private OmsOrderManager omsOrderManager;

    @Override
    public H5DeliveryRespVO getDeliveryById(Long orderId) throws Exception {
        OmsOrder omsOrder = omsOrderManager.verifyAppOrderById(orderId);

        String deliveryInfo = new KdApiSearchUtils().getDelivery(omsOrder.getDeliveryCompany(), omsOrder.getDeliverySn());

        JSONArray traces = JSONUtil.parseObj(deliveryInfo).getJSONArray("Traces");
        List<H5DeliveryRespVO.H5DeliveryItemVO> deliveryInfoVOList = traces.stream()
                .map(trace -> {
                    JSONObject jsonObject = JSONUtil.parseObj(trace);
                    H5DeliveryRespVO.H5DeliveryItemVO h5DeliveryItemVO = new H5DeliveryRespVO.H5DeliveryItemVO();
                    h5DeliveryItemVO.setAcceptTime(jsonObject.getStr("AcceptTime"));
                    h5DeliveryItemVO.setAcceptStation(jsonObject.getStr("AcceptStation"));
                    h5DeliveryItemVO.setRemark(jsonObject.getStr("Remark"));

                    return h5DeliveryItemVO;
                }).collect(Collectors.toList());


        H5DeliveryRespVO h5DeliveryRespVO = new H5DeliveryRespVO();
        h5DeliveryRespVO.setDeliveryInfo(deliveryInfoVOList);
        h5DeliveryRespVO.setDeliveryCompany(omsOrder.getDeliveryCompany());
        h5DeliveryRespVO.setDeliverySn(omsOrder.getDeliverySn());
        return h5DeliveryRespVO;
    }
}
